package com.zhou.framework.filter;

import com.zhou.framework.common.SpringFactory;
import com.zhou.framework.constant.CacheKeyEnum;
import com.zhou.framework.redis.util.RedisUtil;
import com.zhou.framework.xss.request.XssHttpServletRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lang.zhou
 * @date 2022/5/6 14:46
 */
public class XssFilter implements Filter {



    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if (handleExcludeURL(req)) {
            chain.doFilter(request, response);
        }else{
            XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
            chain.doFilter(xssRequest, response);
        }

    }
    private boolean handleExcludeURL(HttpServletRequest request) {
        String uri = request.getRequestURI();
        if(uri.endsWith(".ico") || uri.endsWith(".css") || uri.endsWith(".js")){
            return true;
        }
        RedisUtil redisUtil = SpringFactory.getBean(RedisUtil.class);
        List<Pattern> excludes = redisUtil.get(CacheKeyEnum.XSS_URL);
        if (excludes != null && !excludes.isEmpty()) {
            String url = request.getServletPath();
            for (Pattern p : excludes){
                Matcher m = p.matcher(url);
                if (m.find()){
                    return true;
                }
            }
        }
        return false;
    }
    @Override
    public void destroy() {

    }
}
